import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { View, ScrollView, Image, Swiper, SwiperItem } from '@tarojs/components'
import classnames from 'classnames'
import { debounce, staticUrl } from '@/utils'
import onNavigation from '@/utils/command/onNavigation'
import { getStructure, getContent, getFrontServiceGoods } from '@/api'
import { getGoodsDistributionIndex } from '@/api/goods/distribution'
import { isCurrRoute } from '@/utils/global'
import StoresNavigation from './StoresNavigation'
import Promotion from './Promotion'
import PhotoLayout from './PhotoLayout'
import Mine from './Mine'
import Banner from './Banner'
import './index.scss'

const cartIcon = staticUrl('/img/index/cart-icon.png')

interface Query {
  id?: string | number,
}
interface Layout {
  id?: number
  layoutTitle?: string
  keyword?: string
  layoutType?: number
  layoutTypeLabel?: string
  layoutOrder?: number
  margin?: number
}
interface State {
  city: object
  query: Query | undefined
  backgroundUrl: string | undefined
  backgroundColor: string | undefined
  layoutList: Array<Layout>
  onLoading: boolean
  isFixedMenu: boolean
  tabIndex: number
  classificationArr: [any] | []
  tabLoadingArr: [any] | []
  menuDom: any
  swiperHeight: number
  triggered: boolean
  hotGoodsList: any
}
interface Props {
  city: object,
  query: Query | undefined
}

export default class HomeView extends Component<Props, State> {
  $instance = getCurrentInstance()
  constructor () {
    super(...arguments)
    const props: Props = this.props
    console.log('组件内部的props', props)
    this.state = {
      ...props,
      backgroundUrl: undefined,  // 背景图片
      backgroundColor: undefined,// 主题色
      layoutList: [],// 布局列表
      onLoading: false, // 接口是否请求完成
      isFixedMenu: false, // tab是否 fixed
      tabIndex: 0, // 当前选中tab
      classificationArr: [], // 分类清单列表
      tabLoadingArr: [],//  tab无限加载数组
      swiperHeight: 0,// 分类清单高度
      menuDom: {},// tab高度
      triggered: false, // 下拉刷新是否完成
      hotGoodsList: [],// 分销列表
    }
  }
  state: State

  UNSAFE_componentWillMount() { }
  componentDidMount() {
    // 获取结构
    this.getStructure()
  }

  UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
    let { store } = nextProps
    if (this.state.store && store && store.adCode !== this.state.store.adCode) {
      this.setState({
        ...nextProps
      }, () => {
        // 获取结构
        console.log('是在这儿执行了吗')
        this.getStructure()
      })
    }
  }
  componentWillUnmount() { }

  // 获取结构
  getStructure = async () => {
    console.log('这里面有没有执行了')
    const { query } = this.state
    this.setState({
      onLoading: false
    })
    getStructure({
      id: query ? query.id : undefined
      // id: 42
    }).then(res => {
      const { data: { data } } = res
      // 设置页面导航条颜色
      Taro.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: data.colour,
      })
      Taro.setStorageSync('BarColor', {
        frontColor: '#ffffff',
        backgroundColor: data.colour,
      })
      this.setState({
        backgroundUrl: data.backgroundUrl,
        layoutList: data.layout,
        backgroundColor: data.colour
      }, () => {
        // 获取分销列表
        this.getGoodsDistributionIndex()
        // 获取内容
        const { layoutList } = this.state
        let info = Taro.getStorageSync('CURRENT_LOCATION_INFO')
        layoutList.forEach((val, idx) => {
          getContent({
            data: JSON.stringify({ "data": [{ "id": val.id, "layoutType": val.layoutType, "itemIds": val.itemIds }] }),
            cityCode: info.adCode
          }).then((res) => {
            const { data: { data } } = res
            // val.layoutType == 4 为分类清单 比较特殊 单独处理
            if (val.layoutType == 4) {
              this.classificationList(data[0].content)
            }
            layoutList[idx]['contentList'] = data[0]
            this.setState({
              layoutList,
              onLoading: true
            })
          })
        })
      })
    })
  }

  // 设置分类清单
  classificationList = (arr) => {
    let tabLoadingArr: any = []
    let classificationArr: any = JSON.parse(JSON.stringify(arr))
    arr.map((val, idx) => {
      tabLoadingArr.push([])
      for (let i = val.content.length - 1; i >= 0; i--) {
        if (val.content[i].contentType == 5) {
          tabLoadingArr[idx].push({ id: val.content[i].serviceItems, currPage: 1, dataLength: 0 })
          classificationArr[idx].content.splice(i, 1)
        }
      }
    });

    this.setState({
      classificationArr,
      tabLoadingArr
    }, () => {
      this.calculationHeight()
      console.log('执行domInfo ----- domInfo')
      this.domInfo()
    })
  }

  domInfo = () => {
    // 判断传参是否为当前路由
    if (!isCurrRoute('pages/tabbar/index/index')) return
    let query = Taro.createSelectorQuery();
    Taro.nextTick(() => {
      query.select('.goods-menu').boundingClientRect(rect => {
        this.setState({
          menuDom: rect
        })
      }).exec()
    })
  }

  // 监听页面滑动
  scrollPage = debounce((e) => {
    const { scrollTop } = e.target
    const { menuDom, isFixedMenu } = this.state
    console.log(scrollTop, menuDom)
    //页面没加载完成直接滑动页面，menuDom为null
    if (menuDom && scrollTop >= menuDom.top) {
      if (!isFixedMenu) {
        this.setState({
          isFixedMenu: true
        })
      }
    } else if (!menuDom) {
      this.domInfo()
    } else {
      if (isFixedMenu) {
        this.setState({
          isFixedMenu: false
        })
      }
    }
  }, 10)

  componentDidShow() {
  }

  // 获取分销列表
  getGoodsDistributionIndex = () => {
    getGoodsDistributionIndex({}).then(res => {
      if (res && res.data.success) {
        let arr = res.data.data
        let hotGoodsList = []
        if (arr.length >= 3) {
          // console.log('多于3');
          hotGoodsList = arr.slice(0, 3)
        } else if (arr.length > 0) {
          hotGoodsList = Array(3).fill(arr[0])
        }
        this.setState({
          hotGoodsList
        })
      }
    })
  }

  // 切换标签
  tabGoods = (idx: number) => {
    const { tabIndex } = this.state
    if (tabIndex == idx) return
    // 计算tab高度
    this.calculationHeight()
    this.setState({
      tabIndex: idx
    })
  }

  // 下拉刷新
  onRefresh = async () => {
    const { triggered, onLoading } = this.state
    this.getStructure()
    if (onLoading) {
      await this.setState({
        triggered: !triggered,
      }, () => {
        const { triggered } = this.state
        if (triggered) {
          this.setState({
            triggered: false
          })
        }
      })
    }
  }

  // tab栏
  menuView = () => {
    const { classificationArr, tabIndex } = this.state
    return (
      <View className='goods-menu' >
        <View className='menu'>
          {
            classificationArr.map((v, idx) => {
              return (
                <View key={v.classificationTitle} onClick={() => this.tabGoods(idx)} className={classnames('child-menu', tabIndex === idx && 'curr')}>
                  <View className='text'>{v.classificationTitle}</View>
                </View>
              )
            })
          }
        </View>
      </View>
    )
  }

  // 计算tab高度
  calculationHeight = async () => {
    const { classificationArr, tabIndex } = this.state
    const num = classificationArr[tabIndex].content.length % 2
    const { windowHeight } = await Taro.getSystemInfo();
    let hign = 0
    if (num) {
      hign = (Number(parseInt(String(classificationArr[tabIndex].content.length / 2))) + 1) * 524 + 100
    } else {
      hign = Number(parseInt(String(classificationArr[tabIndex].content.length / 2))) * 524 + 100
    }
    if (hign < Number(windowHeight)) {
      hign = Number(windowHeight)
    }

    this.setState({
      swiperHeight: hign
    })
  }

  // 分类清单滑动时触发
  onChangeSwiper = (e) => {
    const { detail: { current } } = e
    let _that = this
    this.setState({
      tabIndex: current
    }, () => {
      _that.isloadingDate = true
      _that.loadingData()
      // 计算tab高度
      _that.calculationHeight()
    })
  }

  isloadingDate = true
  //加载数据
  loadingData = () => {
    const { tabIndex, tabLoadingArr, classificationArr } = this.state
    if (tabLoadingArr[tabIndex].length == 0) return
    let _that = this

    if (this.isloadingDate) {
      this.isloadingDate = false
      getFrontServiceGoods({
        frontServiceId: tabLoadingArr[tabIndex][0].id,
        currPage: tabLoadingArr[tabIndex][0].currPage
      }).then((res) => {
        const { data: { data }, header } = res
        const total = header['X-Pagination-Total-Count'] //总条数
        this.isloadingDate = true
        // 当查到数组为空时，删除这个 递归查询
        if (data.length == 0) {
          tabLoadingArr[tabIndex].shift()
          return this.setState({
            tabLoadingArr
          }, () => {
            _that.loadingData()
          })
        }
        // 正常请求情况
        tabLoadingArr[tabIndex][0].dataLength += data.length
        tabLoadingArr[tabIndex][0].currPage += 1
        classificationArr[tabIndex].content.push(...data)
        this.setState({
          tabLoadingArr,
          classificationArr
        }, () => {
          // 计算tab高度
          _that.calculationHeight()
        })
        // 如果请求这个前端服务id条数满了，请求下一个
        if (tabLoadingArr[tabIndex][0].dataLength >= total) {
          tabLoadingArr[tabIndex].shift()
          return this.setState({
            tabLoadingArr
          }, () => {
            _that.loadingData()
          })
        }
      })
    }
  }

  render() {
    const { query, backgroundUrl, backgroundColor, layoutList, classificationArr, isFixedMenu, tabIndex, swiperHeight, triggered, hotGoodsList } = this.state
    return <View >
      {/* 头部fixed */}
      <View className="fixed">
        {
          query && query.id && <View className="preview" >当前为预览环境</View>
        }
        {
          classificationArr && isFixedMenu && this.menuView()
        }
      </View>
      <ScrollView
        scrollY
        onScroll={(e) => this.scrollPage(e)}
        refresherEnabled
        refresherTriggered={triggered}
        onRefresherRefresh={() => this.onRefresh()}
        lowerThreshold={200}
        onScrollToLower={() => this.loadingData()}
        className={`box-index ${query && query.id && 'paddingTop50'} alipay-box-index ${process.env.TARO_ENV !== 'weapp'}`}
        style={{ backgroundImage: backgroundUrl ? `url('${backgroundUrl}')` : undefined }}
      >
        {
          // 个人信息
          <Mine color={backgroundColor} />
        }
        {
          layoutList && layoutList.map((item) => {
            switch (Number(item.layoutType)) {
              case 0: // 轮播图
                {
                  return <Banner goods={item} key={item.id} />
                }
              case 1: // 门店导航
                {
                  return <StoresNavigation goods={item} key={item.id} />
                }
              case 2: // 分销组件
                {
                  return <Promotion goods={item} list={hotGoodsList} key={item.id} />
                }
              case 3: // 图片布局
                {
                  return <PhotoLayout goods={item} key={item.id} />
                }
              // case 5: // 门店布局 门店布局隐藏，弱化门店概念
              //   {
              //     return <Store goods={item} store={store} />
              //   }
            }
          })
        }
        {
          classificationArr.length > 0 && (
            <View className="classification">

              <View className='goods-menu' >
                {
                  isFixedMenu ? null : (
                    <View className='menu'>
                      {
                        classificationArr.map((v, idx) => {
                          return (
                            <View key={v.classificationTitle} onClick={() => this.tabGoods(idx)} className={classnames('child-menu', tabIndex === idx && 'curr')}>
                              <View className='text'>{v.classificationTitle}</View>
                            </View>
                          )
                        })
                      }
                    </View>
                  )
                }

              </View>
              <Swiper
                current={tabIndex}
                style={{ height: `${swiperHeight}rpx` }}
                onChange={(e) => this.onChangeSwiper(e)}
              >
                {
                  classificationArr.map((item) => {
                    return (
                      <SwiperItem key={item.classificationTitle} className="swiper-item">
                        <View className='goods-content'>
                          {
                            item.content.map((val) => {
                              return (
                                <View key={val.contentId} className='goods-list' onClick={() => { onNavigation(val) }}>
                                  {
                                    // val.contentType === 0  为首页订单数据， val.thumbnail 为基础服务项目商品列表 接口数据 格式不一样
                                    (val.contentType === 0 || val.thumbnail) ? (
                                      <View>
                                        {
                                          val.thumbnail ? (
                                            <View className='goods-wrap'>
                                              <Image lazyLoad src={val.thumbnail} className='goods-pic'></Image>
                                              <View className='name'>{val.goodsName}</View>
                                              <View className='price-info'>
                                                <View className='price'>{Number(val.vendorSalePrice)}</View>
                                                <Image lazyLoad src={cartIcon} className='cart-img'></Image>
                                              </View>
                                            </View>) :
                                            <View className='goods-wrap'>
                                              <Image lazyLoad src={val.contentImg} className='goods-pic'></Image>
                                              <View className='name'>{val.goodsName}</View>
                                              <View className='price-info'>
                                                <View className='price'>{Number(val.salePrice)}</View>
                                                <Image lazyLoad src={cartIcon} className='cart-img'></Image>
                                              </View>
                                            </View>
                                        }
                                      </View>
                                    ) :
                                      (<Image lazyLoad src={val.contentImg} mode='aspectFill' className='service-goods-pic'></Image>)
                                  }
                                </View>
                              )
                            })
                          }
                        </View>
                        <View className="goods-content-bottom">
                          我是有底线的~
                        </View>
                      </SwiperItem>
                    )
                  })
                }
              </Swiper>
            </View>
          )
        }
      </ScrollView>
    </View>

  }
}
